package cn.liulingfengyu.behavioralpatterns.iteratorpattern;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 迭代器模式示例
 */
public class IteratorPatternDemo {
    public static void main(String[] args) {
        // 创建集合
        Collection collection = new ConcreteCollection();

        // 添加元素
        collection.add("Item 1");
        collection.add("Item 2");
        collection.add("Item 3");

        // 获取迭代器
        Iterator<String> iterator = collection.iterator();

        // 遍历集合
        System.out.println("遍历集合：");
        while (iterator.hasNext()) {
            String item = iterator.next();
            System.out.println(item);
        }

        // 删除元素
        iterator = collection.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            if ("Item 2".equals(item)) {
                iterator.remove();
            }
        }

        // 再次遍历集合
        System.out.println("\n删除 'Item 2' 后遍历集合：");
        iterator = collection.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            System.out.println(item);
        }
    }
}

/**
 * 抽象集合接口
 */
interface Collection {
    void add(String item);
    Iterator<String> iterator();
}

/**
 * 具体集合类
 */
class ConcreteCollection implements Collection {
    private List<String> items = new ArrayList<>();

    @Override
    public void add(String item) {
        items.add(item);
    }

    @Override
    public Iterator<String> iterator() {
        return new ConcreteIterator();
    }

    private class ConcreteIterator implements Iterator<String> {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < items.size();
        }

        @Override
        public String next() {
            return items.get(index++);
        }

        @Override
        public void remove() {
            items.remove(--index);
        }
    }
}